@file:Suppress("SpellCheckingInspection")

package com.hopedove.workshop.api

import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.annotations.SerializedName
import com.hopedove.net.ApiCallResult
import com.hopedove.net.kotlin.CallResult
import com.hopedove.net.kotlin.ErrorResult
import com.hopedove.net.kotlin.SuccessResult
import java.lang.reflect.Type

fun <T> getApiResult(raw: CallResult<String>, type: Type): ApiCallResult<T> {
    return when (raw) {
        is SuccessResult -> {
            val response = Gson().fromJson(raw.value, CommonWorkshopResponse::class.java)
            if (response.isSuccess()) {
                ApiCallResult.Success(
                    Gson().fromJson(response.data, type)
                )
            } else {
                ApiCallResult.Error(error = response.message)
            }
        }
        is ErrorResult -> {
            ApiCallResult.Error(error = raw.error)
        }
    }
}

/**
 *  不关心响应的 DATA 字段，某些接口通常这个字段为空，只想知道调用返回成功或者失败
 */
fun getCommonApiResult(raw: CallResult<String>): ApiCallResult<String> {
    return when (raw) {
        is SuccessResult -> {
            val response = Gson().fromJson(raw.value, CommonWorkshopResponse::class.java)
            if (response.isSuccess()) {
                ApiCallResult.Success("")
            } else {
                ApiCallResult.Error(error = response.message)
            }
        }
        is ErrorResult -> {
            ApiCallResult.Error(error = raw.error)
        }
    }
}

data class CommonWorkshopResponse(
    @SerializedName("FLAG") val flag: String,
    @SerializedName("ERRORMESSAGE") val message: String,
    @SerializedName("DATA") val data: JsonElement
) {
    fun isSuccess(): Boolean = flag == "SUCCESS"
}

data class WorkshopLoginData(
    @SerializedName("XTYHID") val id: String,
    @SerializedName("JSMC") val machineName: String,
    @SerializedName("YHM") val account: String,
    @SerializedName("YHBH") val accountNo: String,
    @SerializedName("XM") val name: String
)